package org.jeecg.modules.middleware.rabbitmq.gen;


import com.alibaba.fastjson.JSONObject;
import com.rabbitmq.client.Channel;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.modules.middleware.rabbitmq.gen.handler.IGenMqHandle;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

@Component
@RabbitListener(bindings = @QueueBinding(
        value = @Queue(value = "genQueue" ,durable = "true"),
        exchange = @Exchange(value = "genExchange", durable = "true",type = ExchangeTypes.DIRECT),
        key = "gen"
))
public class GenRabbitMqListener {

    private ConcurrentHashMap<String, IGenMqHandle> hanlers= new ConcurrentHashMap <>();

    @Autowired
    public GenRabbitMqListener(List<IGenMqHandle> handleList) {
        for (IGenMqHandle iGenMqHandle : handleList) {
            String handlerName = iGenMqHandle.getHandlerName();
            if(StringUtils.isEmpty(handlerName)){
                throw new JeecgBootException("handler error");
            }
            this.hanlers.put(handlerName, iGenMqHandle);
        }
    }

    @RabbitHandler
    public void onMessage(String msg , Message message, Channel channel) throws Exception {
        try {
            JSONObject jo = JSONObject.parseObject(msg);
            String handlerName = jo.getString("handlerName");
            IGenMqHandle iGenMqHandle = hanlers.get(handlerName);
            if(iGenMqHandle != null){
                String c1 = jo.getString("channel");
                String msgContent = jo.getString("msg");
                iGenMqHandle.handle(c1,msgContent);
            }
        }
        catch (Exception e) {
            e.printStackTrace();
        }finally {
            //消费消息
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        }
    }
}
